package com.hunt.controller;

import com.hunt.model.dto.*;
import com.hunt.model.entity.AddressInfo;
import com.hunt.service.ActivityLogService;
import com.hunt.service.ManagementService;
import com.hunt.service.SystemService;
import com.hunt.util.ResponseCode;
import com.hunt.util.Result;
import com.hunt.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author King
 * @Date 2019/11/4/13:37
 * @Description
 */
@Api(value = "用户开号模块")
@Controller
@RequestMapping("account")
public class AccountController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(AccountController.class);
    private  final Pattern chi = Pattern.compile("[\u4e00-\u9fa5]");


    @Autowired
    private ManagementService managementService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ActivityLogService activityLogService;
    

    @ApiOperation(value = "跳转至用户管理模块", httpMethod = "GET", produces = "text/html")
    @RequestMapping(value = "account", method = RequestMethod.GET)
    public String user() {
        return "system/account";
    }

    @ApiOperation(value = "跳转至客服的用户管理模块", httpMethod = "GET", produces = "text/html")
    @RequestMapping(value = "accountforcustomer", method = RequestMethod.GET)
    public String userforcustomer() {
        return "system/accountforcustomer";
    }

    @ApiOperation(value = "跳转至服务器状态模块", httpMethod = "GET", produces = "text/html")
    @RequestMapping(value = "serverstate_page", method = RequestMethod.GET)
    public String serverstate() {
        return "system/serverstate";
    }
    
/*
    @ApiOperation(value = "打开图表页面", httpMethod = "GET", produces = "text/html")
    @RequestMapping(value = "toHistogramPage", method = RequestMethod.GET)
    public String toHistogramPage() {
        return "system/histogram";
    }

*/

    /**
     * 查询用户列表
     *
     * @param page     起始页码
     * @param rows     分页大小
     * @param sort     排序字段
     * @param order    排序规则
     * @param userid   登录ID
     * @param username 中文名
     * @param moneyfrom 资金量开始端点
     * @param moneyto 资金量结束端点
     * @param phone    电话
     * @param address  地址
     * @return
     */
    @ApiOperation(value = "查询用户列表", httpMethod = "GET", produces = "application/json", response = PageInfo.class)
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public PageInfo list(@RequestParam(defaultValue = "1") int page,
                         @RequestParam(defaultValue = "30") int rows,
                         @RequestParam(defaultValue = "zhName") String sort,
                         @RequestParam(defaultValue = "asc") String order,
                         @RequestParam(defaultValue = "", required = false) String userid,
                         @RequestParam(defaultValue = "", required = false) String username,
                         @RequestParam(defaultValue = "0", required = false) Integer moneyfrom,
                         @RequestParam(defaultValue = "2147483647", required = false) Integer moneyto,
                         @RequestParam(defaultValue = "", required = false) String phone,
                         @RequestParam(defaultValue = "", required = false) String address) {
        //因为数据库字段是拉丁,不能有汉语
        Matcher m = chi.matcher(userid);
        if(m.find()){
            userid="";
        }
        PageInfo pageInfo = managementService.selectAccountPage(page, rows, StringUtil.camelToUnderline(sort), order, userid, username, moneyfrom,moneyto, phone, address);
        return pageInfo;
    }

    /**
     * 用于客服查询用户列表
     *
     * @param page     起始页码
     * @param rows     分页大小
     * @param sort     排序字段
     * @param order    排序规则
     * @param userid   登录ID
     * @param username 中文名
     * @param phone    电话
     * @return
     */
    @ApiOperation(value = "客服-查询用户列表", httpMethod = "GET", produces = "application/json", response = PageInfo.class)
    @ResponseBody
    @RequestMapping(value = "listforcustomer", method = RequestMethod.GET)
    public PageInfo listforcustomer(@RequestParam(defaultValue = "1") int page,
                         @RequestParam(defaultValue = "30") int rows,
                         @RequestParam(defaultValue = "zhName") String sort,
                         @RequestParam(defaultValue = "asc") String order,
                         @RequestParam(defaultValue = "", required = false) String userid,
                         @RequestParam(defaultValue = "", required = false) String username,
                         @RequestParam(defaultValue = "", required = false) String phone,
                                    @RequestParam String inselectedloginName) {
        //因为数据库字段是拉丁,不能有汉语
        Matcher m = chi.matcher(userid);
        if(m.find()){
            userid="";
        }
        if (userid != null && !userid.equals("") || username != null && !username.equals("") || phone != null && !phone.equals("")){
            PageInfo pageInfo = managementService.selectAccountPageforcustomer(page, rows, StringUtil.camelToUnderline(sort), order, userid, username,phone);
            //客服操作开号时候增加操作日志记录
            // 获取当前时间
            LocalDateTime operationTime = LocalDateTime.now();
            // 将时间转换成字符串类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String operationTimeStr = formatter.format(operationTime);
            StringJoiner sj = new StringJoiner(", ");
            if (userid != null && !userid.equals("")) {
                sj.add("登录账号："+userid);
            }
            if (username != null && !username.equals("")) {
                sj.add("中文名："+username);
            }
            if (phone != null && !phone.equals("")) {
                sj.add("手机号码："+phone);
            }
            String result = sj.toString();
            activityLogService.insertLog(inselectedloginName, "查询", "搜索信息："+result,operationTimeStr);
            return pageInfo;
        }
        else {
            return null;
        }

    }

    /**
     * 获取地址
     */
    @ApiOperation(value = "查询省市", httpMethod = "GET", produces = "application/json", response = AddressInfo.class)
    @ResponseBody
    @RequestMapping(value = "getarea", method = RequestMethod.GET)
    public List<AddressInfo> areaInfo(@RequestParam(defaultValue = "0",required = false) int code) {
        if(code==0){
            return managementService.findneedarea();
        }
        else {
            return managementService.findneedareabycode(code);
        }

    }
    /**
     * 获取地址
     */
    @ApiOperation(value = "查询所有市", httpMethod = "GET", produces = "application/json", response = AddressInfo.class)
    @ResponseBody
    @RequestMapping(value = "getcity", method = RequestMethod.GET)
    public List<AddressInfo> cityInfo() {
            return managementService.findallcity();
    }
    /**
     * 新增用户
     *
     * @param userid   登录名
     * @param username 中文名
     * @param sex      性别
     * @param money    资金量
     * @param phone    电话
     * @param addressid  地址编码
     * @return
     */
    @ApiOperation(value = "新增用户", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "insertAccount", method = RequestMethod.POST)
    public Result insertAccount(@RequestParam String userid,
                                @RequestParam String username,
                                @RequestParam(defaultValue = "", required = false) String pwd,
                                @RequestParam(defaultValue = "", required = false) String sex,
                                @RequestParam(defaultValue = "0.00", required = false) double money,
                                @RequestParam(defaultValue = "", required = false) String phone,
                                @RequestParam(defaultValue = "", required = false) String addressid,
                                @RequestParam(defaultValue = "", required = false) String userlevel,
                                @RequestParam(defaultValue = "", required = false) String identitycard,
                                @RequestParam(defaultValue = "0", required = false) Integer age,
                                @RequestParam(defaultValue = "", required = false) String address,
                                @RequestParam(defaultValue = "", required = false) Integer exp
    ) {
        //判断是否可查询
        boolean isExistUserId = managementService.isExistUserId(userid);
        if (isExistUserId) {
            return Result.error(ResponseCode.name_already_exist.getMsg());
        }
        //获取用户级别对应到期时间
        UserLevel userLevel = managementService.getUserLevelByid(userlevel);
//        int mDays = userLevel.getEtime();
        int mDays =exp;
        //计算开户时间和到期时间
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        String khTime = f.format(new Date());//开户日期


        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, mDays);// num为增加的天数，可以改变的
        Date mDate = new Date();
        mDate = ca.getTime();
        String enddate = f.format(mDate);


        LoginInfo_new mUserInfo = new LoginInfo_new();
        mUserInfo.setUserid(userid.toLowerCase());
        mUserInfo.setUsername(username);
        mUserInfo.setPwd(pwd);
        mUserInfo.setGroupname("1");
        mUserInfo.setArea("10");
        mUserInfo.setNotlogin(2);
        mUserInfo.setValiddate(enddate);//到期日
        mUserInfo.setViewnews("1");
        mUserInfo.setViewgp(2);
        mUserInfo.setViewqh(10);
        mUserInfo.setViewwp(10);
        mUserInfo.setViewwh(10);
        mUserInfo.setViewgg(10);
        mUserInfo.setUserlevel(userlevel);
        mUserInfo.setMemo_text("10");
        mUserInfo.setViewggmax(0);
        mUserInfo.setViewqhmax(0);
        mUserInfo.setViewwpmax(0);
        mUserInfo.setViewwhmax(0);
        mUserInfo.setViewggmax(0);
        mUserInfo.setUsercfg("|express=mf.fun");
        mUserInfo.setBegintime(1);
        mUserInfo.setEndtime(2);
        mUserInfo.setUsedtotaltime(0.0f);
        mUserInfo.setMax_login_day("3");
        mUserInfo.setKaihutime(khTime);
        mUserInfo.setSex(sex);
        mUserInfo.setMoney(money);
        mUserInfo.setPhone(phone);
        mUserInfo.setAddressid(addressid);
        mUserInfo.setAge(age);
        mUserInfo.setIdentitycard(identitycard);
        mUserInfo.setAddress(address);


        long id = managementService.insertAccount(mUserInfo);
        return Result.success(ResponseCode.success);
    }

    /**
     * 新增用户
     *
     * @param userid   登录名
     * @param username 中文名
     * @param sex      性别
     * @param money    资金量
     * @param phone    电话
     * @param addressid  地址编码
     * @param loginName 登录名(用于记录日志)
     * @return
     */
    @ApiOperation(value = "客服-新增用户", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "insertAccountforcustomer", method = RequestMethod.POST)
    public Result insertAccountforcustomer(@RequestParam String userid,
                                @RequestParam String username,
                                @RequestParam(defaultValue = "", required = false) String pwd,
                                @RequestParam(defaultValue = "", required = false) String sex,
                                @RequestParam(defaultValue = "0.00", required = false) double money,
                                @RequestParam(defaultValue = "", required = false) String phone,
                                @RequestParam(defaultValue = "", required = false) String addressid,
                                @RequestParam(defaultValue = "", required = false) String userlevel,
                                @RequestParam(defaultValue = "", required = false) String identitycard,
                                @RequestParam(defaultValue = "0", required = false) Integer age,
                                @RequestParam(defaultValue = "", required = false) String address,
                                @RequestParam(defaultValue = "", required = false) Integer exp,
                                @RequestParam String loginName
    ) {
        //判断是否可查询
        boolean isExistUserId = managementService.isExistUserId(userid);
        if (isExistUserId) {
            return Result.error(ResponseCode.name_already_exist.getMsg());
        }
        //获取用户级别对应到期时间
        UserLevel userLevel = managementService.getUserLevelByid(userlevel);
//        int mDays = userLevel.getEtime();
        int mDays =exp;
        //计算开户时间和到期时间
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        String khTime = f.format(new Date());//开户日期


        Calendar ca = Calendar.getInstance();
        ca.add(Calendar.DATE, mDays);// num为增加的天数，可以改变的
        Date mDate = new Date();
        mDate = ca.getTime();
        String enddate = f.format(mDate);


        LoginInfo_new mUserInfo = new LoginInfo_new();
        mUserInfo.setUserid(userid.toLowerCase());
        mUserInfo.setUsername(username);
        mUserInfo.setPwd(pwd);
        mUserInfo.setGroupname("1");
        mUserInfo.setArea("10");
        mUserInfo.setNotlogin(2);
        mUserInfo.setValiddate(enddate);//到期日
        mUserInfo.setViewnews("1");
        mUserInfo.setViewgp(2);
        mUserInfo.setViewqh(10);
        mUserInfo.setViewwp(10);
        mUserInfo.setViewwh(10);
        mUserInfo.setViewgg(10);
        mUserInfo.setUserlevel(userlevel);
        mUserInfo.setMemo_text("10");
        mUserInfo.setViewggmax(0);
        mUserInfo.setViewqhmax(0);
        mUserInfo.setViewwpmax(0);
        mUserInfo.setViewwhmax(0);
        mUserInfo.setViewggmax(0);
        mUserInfo.setUsercfg("|express=mf.fun");
        mUserInfo.setBegintime(1);
        mUserInfo.setEndtime(2);
        mUserInfo.setUsedtotaltime(0.0f);
        mUserInfo.setMax_login_day("3");
        mUserInfo.setKaihutime(khTime);
        mUserInfo.setSex(sex);
        mUserInfo.setMoney(money);
        mUserInfo.setPhone(phone);
        mUserInfo.setAddressid(addressid);
        mUserInfo.setAge(age);
        mUserInfo.setIdentitycard(identitycard);
        mUserInfo.setAddress(address);


        long id = managementService.insertAccount(mUserInfo);

        //客服操作开号时候增加操作日志记录
            // 获取当前时间
            LocalDateTime operationTime = LocalDateTime.now();
            // 将时间转换成字符串类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String operationTimeStr = formatter.format(operationTime);
            activityLogService.insertLog(loginName, "开户", "开户id："+userid,operationTimeStr);
        return Result.success(ResponseCode.success);
    }

    /**
     * 更新账号信息
     *
     * @param userid   登录名
     * @param username 中文名
     * @param sex      性别
     * @param money    资金量
     * @param phone    电话
     * @param address  地址
     * @return
     */
    @ApiOperation(value = "更新用户", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "updateAccount", method = RequestMethod.POST)
    public Result updateAccount(@RequestParam String userid,
                                @RequestParam String username,
                                @RequestParam(defaultValue = "", required = false) String pwd,
                                @RequestParam(defaultValue = "", required = false) String sex,
                                @RequestParam(defaultValue = "0", required = false) double money,
                                @RequestParam(defaultValue = "", required = false) String phone,
                                @RequestParam(defaultValue = "", required = false) String addressid,
                                @RequestParam(defaultValue = "", required = false) String userlevel,
                                @RequestParam(defaultValue = "", required = false) String identitycard,
                                @RequestParam(defaultValue = "0", required = false) Integer age,
                                @RequestParam(defaultValue = "", required = false) String address,
                                @RequestParam(defaultValue = "", required = false) Integer exp
    ) throws ParseException {
        //判断是否可查询
        boolean isExistUserId = managementService.isExistUserId(userid);
        if (!isExistUserId) {
            return Result.error("用户不存在");
        }
        LoginInfo_new mUserInfo = new LoginInfo_new();
        mUserInfo.setUserid(userid);
        mUserInfo.setUsername(username);
        mUserInfo.setPwd(pwd);
        mUserInfo.setGroupname("1");
        mUserInfo.setArea("10");
        mUserInfo.setNotlogin(2);

        //计算开户时间和到期时间
        int mDays =exp;
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        String kaihutime = f.format(new Date());//开户日期
        Calendar ca = Calendar.getInstance();
        ca.setTime(f.parse(kaihutime));
        ca.add(Calendar.DATE, mDays);// num为增加的天数，可以改变的
        Date  mDate = ca.getTime();
        String enddate = f.format(mDate);
        mUserInfo.setValiddate(enddate);//到期日

        mUserInfo.setViewnews("1");
        mUserInfo.setViewgp(2);
        mUserInfo.setViewqh(10);
        mUserInfo.setViewwp(10);
        mUserInfo.setViewwh(10);
        mUserInfo.setViewgg(10);
        mUserInfo.setUserlevel(userlevel);
        mUserInfo.setMemo_text("10");
//        mUserInfo.setViewgg_max(0);
//        mUserInfo.setViewqh_max(0);
//        mUserInfo.setViewwp_max(0);
//        mUserInfo.setViewwh_max(0);
//        mUserInfo.setViewgg_max(0);
        mUserInfo.setUsercfg("|express=mf.fun");
        mUserInfo.setBegintime(1);
        mUserInfo.setEndtime(2);
        mUserInfo.setMax_login_day("3");
        //mUserInfo.setKaihutime(khTime);
        mUserInfo.setSex(sex);
        mUserInfo.setMoney(money);
        mUserInfo.setPhone(phone);
        mUserInfo.setAddress(address);
        mUserInfo.setAge(age);
        mUserInfo.setIdentitycard(identitycard);
        mUserInfo.setAddressid(addressid);
        managementService.updateAccount(mUserInfo);
        return Result.success();
    }

    /**
     * 客服-更新账号信息
     *
     * @param userid   登录名
     * @param username 中文名
     * @param sex      性别
     * @param money    资金量
     * @param phone    电话
     * @param address  地址
     * @return
     */
    @ApiOperation(value = "客服-更新用户", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "updateAccountforcustomer", method = RequestMethod.POST)
    public Result updateAccountforcustomer(@RequestParam String userid,
                                @RequestParam String username,
                                @RequestParam(defaultValue = "", required = false) String pwd,
                                @RequestParam(defaultValue = "", required = false) String sex,
                                @RequestParam(defaultValue = "0", required = false) double money,
                                @RequestParam(defaultValue = "", required = false) String phone,
                                @RequestParam(defaultValue = "", required = false) String addressid,
                                @RequestParam(defaultValue = "", required = false) String userlevel,
                                @RequestParam(defaultValue = "", required = false) String identitycard,
                                @RequestParam(defaultValue = "0", required = false) Integer age,
                                @RequestParam(defaultValue = "", required = false) String address,
                                @RequestParam(defaultValue = "", required = false) Integer exp,
                                @RequestParam String loginName
    ) throws ParseException {
        //判断是否可查询
        boolean isExistUserId = managementService.isExistUserId(userid);
        if (!isExistUserId) {
            return Result.error("用户不存在");
        }
        LoginInfo_new mUserInfo = new LoginInfo_new();
        mUserInfo.setUserid(userid);
        mUserInfo.setUsername(username);
        mUserInfo.setPwd(pwd);
        mUserInfo.setGroupname("1");
        mUserInfo.setArea("10");
        mUserInfo.setNotlogin(2);

        //计算开户时间和到期时间
        int mDays =exp;
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        String kaihutime = f.format(new Date());//开户日期
        Calendar ca = Calendar.getInstance();
        ca.setTime(f.parse(kaihutime));
        ca.add(Calendar.DATE, mDays);// num为增加的天数，可以改变的
        Date  mDate = ca.getTime();
        String enddate = f.format(mDate);
        mUserInfo.setValiddate(enddate);//到期日

        mUserInfo.setViewnews("1");
        mUserInfo.setViewgp(2);
        mUserInfo.setViewqh(10);
        mUserInfo.setViewwp(10);
        mUserInfo.setViewwh(10);
        mUserInfo.setViewgg(10);
        mUserInfo.setUserlevel(userlevel);
        mUserInfo.setMemo_text("10");
//        mUserInfo.setViewgg_max(0);
//        mUserInfo.setViewqh_max(0);
//        mUserInfo.setViewwp_max(0);
//        mUserInfo.setViewwh_max(0);
//        mUserInfo.setViewgg_max(0);
        mUserInfo.setUsercfg("|express=mf.fun");
        mUserInfo.setBegintime(1);
        mUserInfo.setEndtime(2);
        mUserInfo.setMax_login_day("3");
        //mUserInfo.setKaihutime(khTime);
        mUserInfo.setSex(sex);
        mUserInfo.setMoney(money);
        mUserInfo.setPhone(phone);
        mUserInfo.setAddress(address);
        mUserInfo.setAge(age);
        mUserInfo.setIdentitycard(identitycard);
        mUserInfo.setAddressid(addressid);

        //查询原始用户数据（用于比对修改的信息）
        LoginInfo_new mOldUserInfo = managementService.selectByLoginName_new(userid);
        //修改用户信息
        managementService.updateAccount(mUserInfo);
        //查询修改后的用户数据
        LoginInfo_new mNewUserInfo = managementService.selectByLoginName_new(userid);
        //客服操作开号时候增加操作日志记录
            // 获取当前时间
            LocalDateTime operationTime = LocalDateTime.now();
            // 将时间转换成字符串类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String operationTimeStr = formatter.format(operationTime);
            String operationContent = "被修改用户的id："+userid+"，修改的内容为：";
        String oldUsername = mOldUserInfo.getUsername() != null ? mOldUserInfo.getUsername() : "";
        String newUsername = mNewUserInfo.getUsername() != null ? mNewUserInfo.getUsername() : "";
        if (!oldUsername.equals(newUsername)){
            operationContent += "用户名："+oldUsername+"->"+newUsername+";";
        }

        String oldUserid = mOldUserInfo.getUserid() != null ? mOldUserInfo.getUserid() : "";
        String newUserid = mNewUserInfo.getUserid() != null ? mNewUserInfo.getUserid() : "";
        if (!oldUserid.equals(newUserid)){
            operationContent += "登录账号："+oldUserid+"->"+newUserid+";";
        }

        String oldPwd = mOldUserInfo.getPwd() != null ? mOldUserInfo.getPwd() : "";
        String newPwd = mNewUserInfo.getPwd() != null ? mNewUserInfo.getPwd() : "";
        if(!oldPwd.equals(newPwd)){
            operationContent += "登录密码："+oldPwd+"->"+newPwd+";";
        }

        String oldUserLevel = "";
        String newUserLevel = "";
        String oldUserlevelVal = mOldUserInfo.getUserlevel() != null ? mOldUserInfo.getUserlevel() : "";
        String newUserlevelVal = mNewUserInfo.getUserlevel() != null ? mNewUserInfo.getUserlevel() : "";
        switch (oldUserlevelVal){
            case "0": oldUserLevel = "体验用户"; break;
            case "1": oldUserLevel = "租用账户"; break;
            case "2": oldUserLevel = "经典账户"; break;
            case "3": oldUserLevel = "尊享账户"; break;
            case "4": oldUserLevel = "标准账户"; break;
            case "5": oldUserLevel = "待定账户1"; break;
            case "6": oldUserLevel = "待定账户2"; break;
        }
        switch (newUserlevelVal){
            case "0": newUserLevel = "体验用户"; break;
            case "1": newUserLevel = "租用账户"; break;
            case "2": newUserLevel = "经典账户"; break;
            case "3": newUserLevel = "尊享账户"; break;
            case "4": newUserLevel = "标准账户"; break;
            case "5": oldUserLevel = "待定账户1"; break;
            case "6": oldUserLevel = "待定账户2"; break;
        }
        if(!oldUserLevel.equals(newUserLevel)){
            operationContent += "指标权限："+oldUserLevel+"->"+newUserLevel+";";
        }

        String oldValiddate = mOldUserInfo.getValiddate() != null ? mOldUserInfo.getValiddate() : "";
        String newValiddate = mNewUserInfo.getValiddate() != null ? mNewUserInfo.getValiddate() : "";
        if(!oldValiddate.equals(newValiddate)){
            operationContent += "到期时间："+oldValiddate+"->"+newValiddate+";";
        }

        String oldSex = "";
        String newSex = "";
        String oldSexVal = mOldUserInfo.getSex() != null ? mOldUserInfo.getSex() : "";
        String newSexVal = mNewUserInfo.getSex() != null ? mNewUserInfo.getSex() : "";
        switch (oldSexVal){
            case "1": oldSex = "男"; break;
            case "2": oldSex = "女"; break;
        }
        switch (newSexVal){
            case "1": newSex = "男"; break;
            case "2": newSex = "女"; break;
        }
        if (!oldSex.equals(newSex)){
            operationContent += "性别："+oldSex+"->"+newSex+";";
        }

        String oldIdentitycard = mOldUserInfo.getIdentitycard() != null ? mOldUserInfo.getIdentitycard() : "";
        String newIdentitycard = mNewUserInfo.getIdentitycard() != null ? mNewUserInfo.getIdentitycard() : "";
        if (!oldIdentitycard.equals(newIdentitycard)){
            operationContent += "身份证号："+oldIdentitycard+"->"+newIdentitycard+";";
        }

        int oldAge = mOldUserInfo.getAge(); // Assuming age is always an integer and cannot be null
        int newAge = mNewUserInfo.getAge(); // Assuming age is always an integer and cannot be null
        if (oldAge != newAge){
            operationContent += "年龄："+oldAge+"->"+newAge+";";
        }

        String oldMoney = mOldUserInfo.getMoney() != null ? String.valueOf(mOldUserInfo.getMoney()) : "";
        String newMoney = mNewUserInfo.getMoney() != null ? String.valueOf(mNewUserInfo.getMoney()) : "";
        if (!oldMoney.equals(newMoney)){
            operationContent += "资金量："+oldMoney+"->"+newMoney+";";
        }

        String oldPhone = mOldUserInfo.getPhone() != null ? mOldUserInfo.getPhone() : "";
        String newPhone = mNewUserInfo.getPhone() != null ? mNewUserInfo.getPhone() : "";
        if (!oldPhone.equals(newPhone)){
            operationContent += "手机号码："+oldPhone+"->"+newPhone+";";
        }

        String oldAddress = mOldUserInfo.getAddress() != null ? mOldUserInfo.getAddress() : "";
        String newAddress = mNewUserInfo.getAddress() != null ? mNewUserInfo.getAddress() : "";
        if (!oldAddress.equals(newAddress)){
            operationContent += "地址："+oldAddress+"->"+newAddress+";";
        }

        activityLogService.insertLog(loginName, "修改", operationContent,operationTimeStr);
        return Result.success();
    }

    /**
     * 更新用户在线状态
     *
     * @param userid     登录名
     * @param viewgp_max 用户在线状态
     * @return
     */
    @ApiOperation(value = "更新用户", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "updateAccountISonline", method = RequestMethod.POST)
    public Result updateAccount(@RequestParam String userid,
                                @RequestParam String viewgp_max,
                                @RequestParam String serverip) {

        //判断是否可查询
        boolean isExistUserId = managementService.isExistUserId(userid);
        if (!isExistUserId) {
            return Result.error("用户不存在");
        }

        LoginInfo_new mUserInfo = new LoginInfo_new();
        mUserInfo.setUserid(userid);
        mUserInfo.setViewgpmax(Integer.parseInt(viewgp_max));

        if (serverip != null && !serverip.equals("")) {
            mUserInfo.setServerip(serverip);
        }
        managementService.updateAccount(mUserInfo);
        return Result.success();
    }

    @ApiOperation(value = "删除账户", httpMethod = "GET", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "deleteAccount", method = RequestMethod.GET)
    public Result deleteAccount(@RequestParam String userid) {

        managementService.deleteAccountById(userid);
        return Result.success();
    }
    /**
     * 客服-删除账户
     *
     */
    @ApiOperation(value = "客服-删除账户", httpMethod = "GET", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "deleteAccountforcustomer", method = RequestMethod.GET)
    public Result deleteAccountforcustomer(@RequestParam String userid,@RequestParam String loginName) {

        managementService.deleteAccountById(userid);
        //客服操作删除用户时候增加操作日志记录
            // 获取当前时间
            LocalDateTime operationTime = LocalDateTime.now();
            // 将时间转换成字符串类型
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String operationTimeStr = formatter.format(operationTime);
            String operationContent = "被删除用户的id："+userid;
            activityLogService.insertLog(loginName, "删除", operationContent,operationTimeStr);
        return Result.success();
    }

    @ApiOperation(value = "重置所有账户登录状态", httpMethod = "GET", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "resetAllAccountState", method = RequestMethod.GET)
    public Result resetAllAccountState() {

        managementService.resetAllAccountState();
        return Result.success();
    }

    @ApiOperation(value = "机构近5日买卖", httpMethod = "GET", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getMechanismTrendFive", method = RequestMethod.GET)
    public Result getMechanismTrendFive() {

        List<MechanismTrend> mResult = managementService.getMechanismTrendFive();
        return Result.success(mResult);
    }

    @ApiOperation(value = "服务器状态", httpMethod = "GET", produces = "application/json;charset=utf-8", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getServerState", method = RequestMethod.GET)
    public PageInfo getServerState() {

        PageInfo pageInfo = managementService.getServerState();

        return pageInfo;
    }

    @ApiOperation(value = "根据serverid取得服务器信息", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getServerMessage", method = RequestMethod.POST)
    public Result getServerMessage(@RequestParam String serverid) {

        List<ServerstateDto> mResult = managementService.getServerMessage(serverid);
        return Result.success(mResult);
    }


    /**
     * 更新用户所在服务器的serverid
     *
     * @param userid       用户ID
     * @param viewgp_max   用户在线状态
     * @param serverip     服务器IP
     * @param serverid     服务器ID
     * @return
     */
    @ApiOperation(value = "更新用户所在服务器的serverid", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "upUserServerId", method = RequestMethod.POST)
    public Result upUserServerId(@RequestParam String userid,
                                 @RequestParam String viewgp_max,
                                 @RequestParam String serverip,
                                 @RequestParam String serverid) {


        //用户存在判断
        boolean isExistUserId = managementService.isExistUserId(userid);
        if (!isExistUserId) {
            return Result.error("用户不存在");
        }
        LoginInfo_new mUserInfo = new LoginInfo_new();
        mUserInfo.setUserid(userid);
        mUserInfo.setViewgpmax(Integer.parseInt(viewgp_max));
        if (serverip != null && !serverip.equals("")) {
            mUserInfo.setServerip(serverip);
        }
        mUserInfo.setServerid(serverid);
        managementService.updateAccount(mUserInfo);
        return Result.success();
    }

    @ApiOperation(value = "在线人数最少的服务器", httpMethod = "GET", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "getFastServerMessage", method = RequestMethod.GET)
    public Result getFastServerMessage() {

        List<ServerstateDto> mTeml = managementService.getFastServerMessage();
        if(mTeml.size() > 0 ){
            List<ServerstateDto> mResult = mTeml.subList(0,1);//取最少人数的服务器信息
            return Result.success(mResult);
        }else{
            return Result.error();
        }

    }
//    /**
//     * 更新阿里云服务器状态
//     *
//     * @param serverip     登录名
//     * @param state        服务器状态
//     * @return
//     */
//    @ApiOperation(value = "更新服务器状态", httpMethod = "POST", produces = "application/json", response = Result.class)
//    @ResponseBody
//    @RequestMapping(value = "updateAccountISonline", method = RequestMethod.POST)
//    public Result updateAccount(@RequestParam String serverip,
//                                @RequestParam String state) {
//
//        //判断是否可查询
//        boolean isExistUserId = managementService.isExistUserId(userid);
//        if (!isExistUserId) {
//            return Result.error("用户不存在");
//        }
//
//        LoginInfo_new mUserInfo = new LoginInfo_new();
//        mUserInfo.setUserid(userid);
//        mUserInfo.setViewgpmax(Integer.parseInt(viewgp_max));
//
//        if(serverip!=null && !serverip.equals("")){
//            mUserInfo.setServerip(serverip);
//        }
//        managementService.updateAccount(mUserInfo);
//        return Result.success();
//    }


}
